const logger = require('../helper/logger')

const tableName = 'utility_token'

module.exports = async (db) => {
  try {
    const exists = await db.schema.hasTable(tableName)
    if (!exists) {
      await db.schema.createTable(tableName, (table) => {
        table.charset('utf8')
        table.increments('id')
        table.string('token', 64).unique()
        table.enum(
          'type',
          [
            'reset_password',
            'provider_invite',
            'provider_organisation_invite',
          ],
        ).notNullable()
        table.dateTime('expired_at').notNullable()
        table.integer('administrator_id').unsigned()
        table.foreign('administrator_id').references('id').inTable('administrator')
        table.integer('merchant_id').unsigned()
        table.foreign('merchant_id').references('id').inTable('merchant')
        table.integer('user_id').unsigned()
        table.foreign('user_id').references('id').inTable('user')
        table.enum('app', ['admin', 'merchant', 'client']).notNullable()
        table.enum('device', ['android', 'ios', 'web']).notNullable()
        table.string('app_version')
        table.string('device_version')
        table.string('remark')
        table.timestamps(false, true)
      })
      logger.info(`Created ${tableName} table`)
    }
  } catch (error) {
    logger.error(`Error creating ${tableName} table`, error)
  }
}
